import java.sql.*;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;


public class Database {
	Context initCtx;
	Context envCtx;
	DataSource ds;
	Connection con;
	Statement query;
	ResultSet rs;
	StringBuilder SQLquery;
	Database() throws SQLException{
		initCtx = null;
		envCtx = null;
		ds = null;
		con = null;
		query = null;
		rs = null;
		SQLquery = new StringBuilder();
		try {
			initCtx = new InitialContext();
			envCtx = (Context)initCtx.lookup("java:/comp/env");
			ds = (DataSource)envCtx.lookup("jdbc/Bazi");
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}
	
	void Close() throws SQLException{
		con.close();
	}
	
	Database Exec(String Procedure_name, String values){
		SQLquery.append("begin " + Procedure_name + "("+ values + "); end;");
		return this;
	}
	
	ResultSet GetResult() throws SQLException{
		if(con==null){
			con = ds.getConnection();
		}
		if(query == null){
			query = con.createStatement();
		}
		rs = query.executeQuery(SQLquery.toString());
		return rs;
	}
	void execute() throws SQLException{
		if(con == null){
			con = ds.getConnection();
		}
		query = con.createStatement();
		query.execute(SQLquery.toString());
	}
	PreparedStatement SafeInput() throws SQLException{
		if(con == null){
			con = ds.getConnection();
		}
		return con.prepareStatement(SQLquery.toString());

	}
	Database Select(String Atributes){
		SQLquery.append("SELECT ");
		SQLquery.append(Atributes);
		return this;
	}
	
	Database From(String Tables){
		SQLquery.append("\nFROM ");
		SQLquery.append(Tables);
		return this;
	}
	Database Where(String Conditions){
		SQLquery.append("\nWHERE ");
		SQLquery.append(Conditions);
		return this;
	}
	Database GroupBy(String Options){
		SQLquery.append("\nGROUP BY ");
		SQLquery.append(Options);
		return this;
	}
	Database OrderBy(String Options){
		SQLquery.append("\nORDER BY ");
		SQLquery.append(Options);
		return this;
	}
	Database InsertInto(String Tables){
		SQLquery.append("INSERT INTO ");
		SQLquery.append( Tables);
		return this;
	}
	Database Values(String Values){
		SQLquery.append("\nVALUES (");
		SQLquery.append(Values);
		SQLquery.append(")");
		return this;
	}
	Database Update(String Table){
		SQLquery.append("UPDATE ");
		SQLquery.append(Table);
		return this;
	}
	Database Set(String Arguments){
		SQLquery.append("\n");
		SQLquery.append("SET ");
		SQLquery.append(Arguments);
		return this;
	}
}
